"""
Copyright (c) 2024 Beijing Jiaotong University
PhotLab is licensed under [Open Source License].
You can use this software according to the terms and conditions of the [Open Source License].
You may obtain a copy of [Open Source License] at: [https://open.source.license/]

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.

See the [Open Source License] for more details.

Author: Yunzhou Tang
Created: 2024/03/08
Supported by: National Key Research and Development Program of China
"""

from . import *
import numpy as np


def receiver_B2B(
    signals,
    bits_per_symbol: int = 4,
    total_baud: float = 60e9,
    up_sampling_factor: int = 4,
    roll_off: float = 0.01,
    num_tap: int = 25,
    ref_power_cma: int = 2,
    cma_convergence: int = 33000,
    step_size_cma: float = 1e-9,
    step_size_rde: float = 1e-9,
    num_test_angle: int = 64,
    block_size: int = 120
):
    prev_symbols = [signals[1], signals[2]]
    signals = np.array(signals[0])
    # 更改数据格式
    s1 = np.expand_dims(signals[0:, 0], axis=1)
    s2 = np.expand_dims(signals[0:, 1], axis=1)
    signals = [s1, s2]

    """ IQ正交化补偿，就是将之前的I/Q失衡的损伤补偿回来 """
    signals = iq_compensation(signals)   # 自己的方案

    """ 粗糙的频偏估计和补偿 """
    sampling_rate = up_sampling_factor * total_baud  # 信号采样率
    signals = freq_offset_compensation(signals, sampling_rate)

    """ 接收端相应的RRC脉冲整形，具体的参数代码与发射端的RRC滤波器是一致的 """
    signals = pulse_shaper(
        signals, up_sampling_factor, roll_off, total_baud)

    """ 帧同步，寻找与发射端原始信号头部对应的符号 """
    signals, prev_symbols = synchronization(
        signals, prev_symbols, up_sampling_factor)

    """ 自适应均衡，此处采用恒模算法（CMA）对收敛系数进行预收敛，再拿收敛后的滤波器系数对正式的信号使用半径定向算法（RDE）进行均衡收敛，"""
    signals = adaptive_equalizer(
        signals,
        num_tap,
        cma_convergence,
        ref_power_cma,
        step_size_cma,
        step_size_rde,
        up_sampling_factor,
        bits_per_symbol,
        total_baud,
    )

    """ 均衡后进行精确的频偏估计和补偿 采用FFT-FOE算法，"""
    signals = freq_offset_compensation(signals, total_baud)

    """ 相位恢复  采用盲相位搜索算法（BPS）进行相位估计和补偿 """

    signals = bps_restore(
        signals, num_test_angle, block_size, bits_per_symbol)

    return signals
